<?php
/**
 * [YIZHIKEJI System] Copyright (c) 2014 yz929.cn
 * YIZHIKEJI is NOT a free software, it under the license terms, visited http://www.yz929.cn/ for more details.
 */
defined('IN_IA') or exit('Access Denied');

function users_module_create($user_module){
    $apend = array(
        'addtime' =>strtotime(date('Y-m-d')),
        'status' => 1,//默认状态为1，可用
    );
    $result = pdo_insert('users_modules',array_merge($apend,$user_module));
    return $result;
}
//获得所有模块
function modules_get($web_uid){
    $modules = pdo_fetchall('select m.*,um.deadline from '.tablename('modules').' m inner join '.tablename('users_modules').' um on m.mid=um.mid where um.uid=:uid',array('uid'=>$web_uid));
    return $modules;
}
///获取有效模块
function modules_getValid($web_uid){
    $modules = modules_get($web_uid);
    $temp = array();
    $i = 0;
    foreach ($modules as $module){
        if($module['deadline']>strtotime(date('Y-m-d'))||$module['deadline']==-1){
            $temp[$i] = $module;
            $i++;
        }
    }
    unset($modules);
    return $temp;
}
//过期模块
function modules_getInvalid($web_uid){
    $modules = modules_get($web_uid);
    $temp = array();
    $i = 0;
    foreach ($modules as $module){
        if($module['deadline']<=strtotime(date('Y-m-d'))&&$module['deadline']!=-1){
            $temp[$i] = $module;
            $i++;
        }
    }
    unset($modules);
    return $temp;
}

function module_types()
{
    static $types = array(
        'business' => array(
            'name' => 'business',
            'title' => '主要业务',
            'desc' => ''
        ),
        'customer' => array(
            'name' => 'customer',
            'title' => '客户关系',
            'desc' => ''
        ),
        'activity' => array(
            'name' => 'activity',
            'title' => '营销及活动',
            'desc' => ''
        ),
        'wdlgame' => array(
            'name' => 'wdlgame',
            'title' => '游戏应用',
            'desc' => ''
        ),
        'wdlshow' => array(
            'name' => 'wdlshow',
            'title' => '展示应用',
            'desc' => ''
        ),
        'services' => array(
            'name' => 'services',
            'title' => '常用服务及工具',
            'desc' => ''
        ),
        'biz' => array(
            'name' => 'biz',
            'title' => '行业解决方案',
            'desc' => ''
        ),
        'other' => array(
            'name' => 'other',
            'title' => '其他',
            'desc' => ''
        )
    );
    return $types;
}


function module_entries($name, $types = array(), $rid = 0, $args = null)
{
    global $_W;
    $ts = array('rule', 'cover', 'menu', 'home', 'profile', 'shortcut', 'function', 'mine');
    if (empty($types)) {
        $types = $ts;
    } else {
        $types = array_intersect($types, $ts);
    }
    $fields = implode("','", $types);
    $sql = 'SELECT * FROM ' . tablename('modules_bindings') . " WHERE `module`=:module AND `entry` IN ('{$fields}') ORDER BY displayorder DESC, eid ASC";
    $pars = array();
    $pars[':module'] = $name;
    $bindings = pdo_fetchall($sql, $pars);
    $entries = array();
    foreach ($bindings as $bind) {
        if (!empty($bind['call'])) {
            $extra = array();
            $extra['Host'] = $_SERVER['HTTP_HOST'];
            load()->func('communication');
            $urlset = parse_url($_W['siteurl']);
            $urlset = pathinfo($urlset['path']);
            $response = ihttp_request('http://127.0.0.1/' . $urlset['dirname'] . '/' . url('utility/bindcall', array('modulename' => $bind['module'], 'callname' => $bind['call'], 'args' => $args, 'uniacid' => $_W['uniacid'])), array('W' => base64_encode(iserializer($_W))), $extra);
            if (is_error($response)) {
                continue;
            }
            $response = json_decode($response['content'], true);
            $ret = $response['message'];
            if (is_array($ret)) {
                foreach ($ret as $et) {
                    $et['url'] .= '&__title=' . urlencode($et['title']);
                    $entries[$bind['entry']][] = array('title' => $et['title'], 'do' => $et['do'], 'url' => $et['url'], 'from' => 'call', 'icon' => $et['icon'], 'displayorder' => $et['displayorder']);
                }
            }
        } else {
            if ($bind['entry'] == 'cover') {
                $url = wurl("platform/cover", array('eid' => $bind['eid']));
            }
            if ($bind['entry'] == 'menu') {
                $url = wurl("site/entry", array('eid' => $bind['eid']));
            }
            if ($bind['entry'] == 'mine') {
                $url = $bind['url'];
            }
            if ($bind['entry'] == 'rule') {
                $par = array('eid' => $bind['eid']);
                if (!empty($rid)) {
                    $par['id'] = $rid;
                }
                $url = wurl("site/entry", $par);
            }
            if ($bind['entry'] == 'home') {
                $url = murl("entry", array('eid' => $bind['eid']));
            }
            if ($bind['entry'] == 'profile') {
                $url = murl("entry", array('eid' => $bind['eid']));
            }
            if ($bind['entry'] == 'shortcut') {
                $url = murl("entry", array('eid' => $bind['eid']));
            }
            if (empty($bind['icon'])) {
                $bind['icon'] = 'fa fa-puzzle-piece';
            }
            $entries[$bind['entry']][] = array('eid' => $bind['eid'], 'title' => $bind['title'], 'do' => $bind['do'], 'url' => $url, 'from' => 'define', 'icon' => $bind['icon'], 'displayorder' => $bind['displayorder'], 'direct' => $bind['direct']);
        }
    }
    return $entries;
}

function module_app_entries($name, $types = array(), $args = null)
{
    global $_W;
    $ts = array('rule', 'cover', 'menu', 'home', 'profile', 'shortcut', 'function');
    if (empty($types)) {
        $types = $ts;
    } else {
        $types = array_intersect($types, $ts);
    }
    $fields = implode("','", $types);
    $sql = 'SELECT * FROM ' . tablename('modules_bindings') . " WHERE `module`=:module AND `entry` IN ('{$fields}') ORDER BY eid ASC";
    $pars = array();
    $pars[':module'] = $name;
    $bindings = pdo_fetchall($sql, $pars);
    $entries = array();
    foreach ($bindings as $bind) {
        if (!empty($bind['call'])) {
            $extra = array();
            $extra['Host'] = $_SERVER['HTTP_HOST'];
            load()->func('communication');
            $urlset = parse_url($_W['siteurl']);
            $urlset = pathinfo($urlset['path']);
            $response = ihttp_request('http://127.0.0.1/' . $urlset['dirname'] . '/' . url('utility/bindcall', array('modulename' => $bind['module'], 'callname' => $bind['call'], 'args' => $args, 'uniacid' => $_W['uniacid'])), array('W' => base64_encode(iserializer($_W))), $extra);
            if (is_error($response)) {
                continue;
            }
            $response = json_decode($response['content'], true);
            $ret = $response['message'];
            if (is_array($ret)) {
                foreach ($ret as $et) {
                    $et['url'] .= '&__title=' . urlencode($et['title']);
                    $entries[$bind['entry']][] = array('title' => $et['title'], 'url' => $et['url'], 'from' => 'call');
                }
            }
        } else {
            if ($bind['entry'] == 'cover') {
                $url = murl("entry", array('eid' => $bind['eid']));
            }
            if ($bind['entry'] == 'home') {
                $url = murl("entry", array('eid' => $bind['eid']));
            }
            if ($bind['entry'] == 'profile') {
                $url = murl("entry", array('eid' => $bind['eid']));
            }
            if ($bind['entry'] == 'shortcut') {
                $url = murl("entry", array('eid' => $bind['eid']));
            }
            $entries[$bind['entry']][] = array('title' => $bind['title'], 'do' => $bind['do'], 'url' => $url, 'from' => 'define');
        }
    }
    return $entries;
}


function module_build_form($name, $rid)
{
    $rid = intval($rid);
    $m = WeUtility::createModule($name);
    return $m->fieldsFormDisplay($rid);
}


function module_fetch($name)
{
    $modules = uni_modules();
    return $modules[$name];
}


function module_build_privileges()
{
    $uniacid_arr = pdo_fetchall('SELECT uniacid FROM ' . tablename('uni_account'));
    foreach ($uniacid_arr as $row) {
        $owneruid = pdo_fetchcolumn("SELECT uid FROM " . tablename('uni_account_users') . " WHERE uniacid = :uniacid AND role = 'owner'", array(':uniacid' => $row['uniacid']));
        load()->model('user');
        $owner = user_single(array('uid' => $owneruid));
        if (empty($owner)) {
            $groupid = '-1';
        } else {
            $groupid = $owner['groupid'];
        }
        $modules = array();
        if (empty($groupid)) {
            return true;
        } elseif ($groupid == '-1') {
            $modules = pdo_fetchall("SELECT name FROM " . tablename('modules') . ' WHERE issystem = 0', array(), 'name');
        } else {
            $group = pdo_fetch("SELECT id, name, package FROM " . tablename('users_group') . " WHERE id = :id", array(':id' => $groupid));
            $packageids = iunserializer($group['package']);
            if (empty($packageids)) {
                return true;
            }
            if (in_array('-1', $packageids)) {
                $modules = pdo_fetchall("SELECT name FROM " . tablename('modules') . ' WHERE issystem = 0', array(), 'name');
            } else {
                $wechatgroup = pdo_fetchall("SELECT `modules` FROM " . tablename('uni_group') . " WHERE id IN ('" . implode("','", $packageids) . "') OR uniacid = '{$row['uniacid']}'");
                if (!empty($wechatgroup)) {
                    foreach ($wechatgroup as $li) {
                        $li['modules'] = iunserializer($li['modules']);
                        if (!empty($li['modules'])) {
                            foreach ($li['modules'] as $modulename) {
                                $modules[$modulename] = $modulename;
                            }
                        }
                    }
                }
            }
        }
        $modules = array_keys($modules);
        $mymodules = pdo_fetchall("SELECT `module` FROM " . tablename('uni_account_modules') . " WHERE uniacid = '{$row['uniacid']}' ORDER BY enabled DESC ", array(), 'module');
        $mymodules = array_keys($mymodules);
        foreach ($modules as $module) {
            if (!in_array($module, $mymodules)) {
                $data = array();
                $data['uniacid'] = $row['uniacid'];
                $data['module'] = $module;
                $data['enabled'] = 1;
                $data['settings'] = '';
                pdo_insert('uni_account_modules', $data);
            }
        }
    }
    return true;
}
